//
//  NetWork.m
//  HongQiao
//
//  Created by maple on 16/11/30.
//  Copyright © 2016年 MapleDongSen. All rights reserved.
//

#import "NetWork.h"
#import "HUDManager.h"
#import "NetWork+BodyAndCookie.h"
#import "NetWorkType.h"
#import "AlertViewManager.h"
//#import "Utility.h"
@implementation NetWork
+(void)PostNetWorkWithUrl:(NSString *)url with:(NSDictionary *)dic successBlock:(SuccessCallBack)dicback FailureBlock:(FailureCallBack)msgback errorBlock:(ErrorCallBack)errorblock
{
    if ([NetWorkType CheckNetWorkType]== NetWorkTypesNoNe ) {
        errorblock(@"没有网络");
        [HUDManager hideHUDView];
//        [Utility alert:@"网络连接不可用"];
        return;
    }
    NSString * postUrl = [NSString stringWithFormat:@"%@%@",SERVER_NEW_NETWORK_PRODUCT,url];
    //接口空字符去掉
    NSString * postReplaceUrls = [postUrl stringByReplacingOccurrencesOfString:@" " withString:@""];
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    //设置请求头
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json",@"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain",  nil]];
    
    [self setHttpCookie];
    
    [manager POST:postReplaceUrls parameters:dic progress:^(NSProgress * _Nonnull uploadProgress)
     {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
    {
        [self getHttpCookie];
        [HUDManager hideHUDView];
        NSDictionary * content = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if ([content[@"status"] integerValue] == 0  ) {
            NSDictionary *datadic = content[@"data"];
            if (datadic) {
                dicback(content);
            }else{
                msgback(@"没有数据");
            }
        }else if ([content[@"status"] integerValue] == 5){
            /**用户过期*/
            [AlertViewManager showAlertViewSuccessedMessage:@"登录状态已取消!\n可能在别的设备登录！请重新登录！" handlerBlock:^{
                [[UserAccountManager shareUserAccountManager]logout];
            }];
        }
        else{
            msgback(content[@"message"]?:@"");
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
    {
        [HUDManager hideHUDView];
        [HUDManager showWarningWithText:@"连接异常"];
        errorblock(error);
    }];
}

+(void)GetNetWorkWithUrl:(NSString *)url with:(NSDictionary *)dic successBlock:(SuccessCallBack)dicback FailureBlock:(FailureCallBack)msgback errorBlock:(ErrorCallBack)errorblock
{
    NSString * postUrl = [NSString stringWithFormat:@"%@%@",SERVER_NEW_NETWORK_PRODUCT,url];
    //接口空字符去掉
    NSString * postReplaceUrls = [postUrl stringByReplacingOccurrencesOfString:@" " withString:@""];
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //设置请求头
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", nil]];
    [manager GET:postReplaceUrls parameters:dic progress:^(NSProgress * _Nonnull uploadProgress)
     {
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         NSDictionary * content = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
         if ([content[@"status"] integerValue] == 1) {
             NSDictionary *datadic = content[@"data"];
             if (datadic) {
                 dicback(content);
             }else{
                 msgback(@"没有数据");
             }
         }else{
             msgback(content[@"message"]?:@"");
         }
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         errorblock(error);
     }];
    
    
    
}

+ (void)PostUpLoadImageWithImages:(NSArray *)images withID:(NSString *)prudectId successBlock:(PhotoSuccessCallBack)dicback FailureBlock:(FailureCallBack)msgback errorBlock:(ErrorCallBack)errorblock
{
//    if ([NetWorkType CheckNetWorkType]==NetWorkTypesNoNe) {
//        errorblock(@"没有网络");
//        [HUDManager hideHUDView];
//        //        [Utility alert:@"网络连接不可用"];
//        return;
//    }
//    //接口拼接
//    NSString * postUrl = [NSString stringWithFormat:@"%@%@",SERVER_NEW_NETWORK_PRODUCT,@"api/user/upload.ajax"];
//    //接口空字符去掉
//    NSString * postReplaceUrls = [postUrl stringByReplacingOccurrencesOfString:@" " withString:@""];
//    //图片data
//
//    //图片名称
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    formatter.dateFormat = @"yyyyMMddHHmmss";
//    NSString * str = [formatter stringFromDate:[NSDate date]];
//
//    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.securityPolicy.allowInvalidCertificates = YES;
//    manager.securityPolicy.validatesDomainName = NO;
//
//    //设置请求头
//    //    [NetWork setHttpBody:manager.requestSerializer];
//    [NetWork setHttpCookie];
//    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", nil]];
//
//    __block NSData * imageData = nil;
//
//    [manager POST:postReplaceUrls parameters:@{@"id":prudectId?:@"",@"token":kTokenID} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        // 上传图片，以文件流的格式
//        __block NSString * fileName = nil;
//        [images enumerateObjectsUsingBlock:^(UIImage *  _Nonnull image, NSUInteger idx, BOOL * _Nonnull stop) {
//            fileName = [NSString stringWithFormat:@"%@_%lu.jpg", str,(unsigned long)idx];
//            imageData = UIImageJPEGRepresentation(image, .5);
//            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg"];
//        }];
//
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//
//
//
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        [HUDManager hideHUDView];
//        NSDictionary *content = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
//        if ([content[@"status"] integerValue] == 0  ) {
//            NSDictionary *datadic = content[@"data"];
//            if (datadic) {
//                dicback(content);
//            }else{
//                msgback(@"没有数据");
//            }
//        }else if ([content[@"status"] integerValue] == 5){
//            /**用户过期*/
//            [AlertViewManager showAlertViewSuccessedMessage:@"登录状态已取消!\n可能在别的设备登录！请重新登录！" handlerBlock:^{
//                [[UserAccountManager shareUserAccountManager]logout];
//            }];
//        }
//        else{
//            msgback(content[@"message"]?:@"");
//        }
//
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [HUDManager hideHUDView];
//        errorblock(error);
//
//
//    }];
    NSInteger totalcount= 0;
    for (int i=0; i<images.count ; i++) {
        if ([images[i] isKindOfClass:[UIImage class]] ||![images[i] isEqualToString:@""]) {
            totalcount ++;
        }
    }
    if (totalcount == 0){
        [HUDManager showWarningWithText:@"没有修改！无需保存！"];
        return;
    }
    
    
    dispatch_queue_t defaultQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
    dispatch_semaphore_t semaphore=dispatch_semaphore_create(1);
    
    __block NSInteger count= 0;
    
    for (int i=0; i<images.count ; i++) {
        dispatch_async(defaultQueue, ^{
        
        dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
            if ([images[i] isKindOfClass:[UIImage class]] ||![images[i] isEqualToString:@""]) {
                [NetWork PostUpLoadImageWithImages:images[i] index:i pid:prudectId successBlock:^(NSString *imagePath) {
                    count ++;
                    UpLoadModelManager *manager = [UpLoadModelManager sharedInstance];
                    [manager.model setValue:imagePath forKey:[NSString stringWithFormat:@"imageurl%d",i+1]];
                    if (count == totalcount) {
                        [HUDManager hideHUDView];
                        dicback(imagePath);
                    }
                    
                } FailureBlock:^(NSString *msg) {
                    [HUDManager hideHUDView];
                    msgback(@"上传失败请重试");
                    
                } errorBlock:^(id error) {
                    [HUDManager hideHUDView];
                    msgback(@"上传失败请重试");
                }];
            }
        
            
        dispatch_semaphore_signal(semaphore);
            
        });
    }
}





+ (void)PostUpLoadImageWithImages:(UIImage *)image index:(NSInteger )index pid:(NSString *)pid successBlock:(PhotoSuccessCallBack)dicback FailureBlock:(FailureCallBack)msgback errorBlock:(ErrorCallBack)errorblock
{
    if ([NetWorkType CheckNetWorkType]==NetWorkTypesNoNe) {
        errorblock(@"没有网络");
        [HUDManager hideHUDView];
//        [Utility alert:@"网络连接不可用"];
        return;
    }
    //接口拼接
    NSString * postUrl = [NSString stringWithFormat:@"%@%@",SERVER_NEW_NETWORK_PRODUCT,@"api/user/upload.ajax"];
    //接口空字符去掉
    NSString * postReplaceUrls = [postUrl stringByReplacingOccurrencesOfString:@" " withString:@""];
    //图片data
    
    //图片名称
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString * str = [formatter stringFromDate:[NSDate date]];
    
    str = [NSString stringWithFormat:@"%@_%ld",str,(long)index];
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy.validatesDomainName = NO;
    
    //设置请求头
//    [NetWork setHttpBody:manager.requestSerializer];
    [NetWork setHttpCookie];
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", nil]];
    
    __block NSData * imageData = nil;
    
    [manager POST:postReplaceUrls parameters:@{@"id":pid?:@"",@"token":kTokenID} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        __block NSString * fileName = nil;
        fileName = [NSString stringWithFormat:@"%@.jpg", str];
        imageData = UIImageJPEGRepresentation(image, .5);
        [formData appendPartWithFileData:imageData name:@"imgFile" fileName:fileName mimeType:@"image/jpg"];

    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *content = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        if ([content[@"status"] integerValue] == 0  ) {
            NSDictionary *datadic = content[@"data"];
            if (datadic) {
                NSString *urls = [datadic[@"domain"] stringByAppendingString:datadic[@"url"]];
                dicback(urls);
            }else{
                msgback(@"没有数据");
            }
        }else if ([content[@"status"] integerValue] == 5){
            /**用户过期*/
            [AlertViewManager showAlertViewSuccessedMessage:@"登录状态已取消!\n可能在别的设备登录！请重新登录！" handlerBlock:^{
                [[UserAccountManager shareUserAccountManager]logout];
            }];
        }
        else{
            msgback(content[@"message"]?:@"");
        }

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        errorblock(error);
    }];
}
+ (void)PostUpLoadAudioWithData:(NSData *)audiodata successBlock:(PhotoSuccessCallBack)dicback FailureBlock:(FailureCallBack)msgback errorBlock:(ErrorCallBack)errorblock{
    
    if ([NetWorkType CheckNetWorkType]==NetWorkTypesNoNe) {
        errorblock(@"没有网络");
        [HUDManager hideHUDView];
//        [Utility alert:@"网络连接不可用"];
        return;
    }
    //接口拼接
    NSString * postUrl = [NSString stringWithFormat:@"%@%@",SERVER_NEW_NETWORK_PRODUCT,@"upload"];
    //接口空字符去掉
    NSString * postReplaceUrls = [postUrl stringByReplacingOccurrencesOfString:@" " withString:@""];
    //图片data
    
    //图片名称
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString * str = [formatter stringFromDate:[NSDate date]];
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy.validatesDomainName = NO;
    
    //设置请求头
    //    [NetWork setHttpBody:manager.requestSerializer];
    [NetWork setHttpCookie];
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", nil]];
    
    __block NSData * AData = nil;
    
    [manager POST:postReplaceUrls parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        __block NSString * fileName = nil;
        fileName = [NSString stringWithFormat:@"%@.mp3", str];
        AData = audiodata;
        [formData appendPartWithFileData:AData name:@"imgurl_file" fileName:fileName mimeType:@"audio/mp3"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *content = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        if ([content[@"status"] integerValue] == 0  ) {
            NSDictionary *datadic = content[@"data"];
            if (datadic) {
                dicback(content);
            }else{
                msgback(@"没有数据");
            }
        }else if ([content[@"status"] integerValue] == 5){
            /**用户过期*/
            [AlertViewManager showAlertViewSuccessedMessage:@"登录状态已取消!\n可能在别的设备登录！请重新登录！" handlerBlock:^{
                [[UserAccountManager shareUserAccountManager]logout];
            }];
        }
        else{
            msgback(content[@"message"]?:@"");
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        errorblock(error);
        
        
    }];

}
@end
